package org.example.springboot.controller;

import org.example.springboot.entity.Expert;
import org.example.springboot.entity.ExpertAppointment;
import org.example.springboot.entity.User;
import org.example.springboot.mapper.UserMapper;
import org.example.springboot.repository.ExpertRepository;
import org.example.springboot.service.ExpertAppointmentService;
import org.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author reisen7
 * @date 2025/5/29 21:16
 * @description 
 */

@RestController
@RequestMapping("/api/appointments")
public class ExpertAppointmentController {
    @Autowired
    private ExpertAppointmentService expertAppointmentService;

    @Autowired
    private ExpertRepository expertRepository;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/expert/{expertId}")
    public List<ExpertAppointment> getAppointmentsByExpert(@PathVariable Long expertId) {
        List<ExpertAppointment> byExpertId = expertAppointmentService.findByExpertId(expertId);
        byExpertId.forEach(expertAppointment -> {
            expertAppointment.setName(userMapper.selectById(expertAppointment.getUserId()).getName());
        });

        return expertAppointmentService.findByExpertId(expertId);
    }

    @GetMapping("/user/{userId}")
    public List<ExpertAppointment> getAppointmentsByUser(@PathVariable Long userId) {

        List<ExpertAppointment> byUserId = expertAppointmentService.findByUserId(userId);
        byUserId.forEach(expertAppointment -> {
            expertAppointment.setExpertName(expertRepository.findByUserId(expertAppointment.getExpertId()).getName());
        });

        return expertAppointmentService.findByUserId(userId);
    }

    @GetMapping("/{id}")
    public ExpertAppointment getAppointmentById(@PathVariable Long id) {
        return expertAppointmentService.findById(id);
    }

    @PostMapping
    public ExpertAppointment createAppointment(@RequestBody ExpertAppointment appointment) {

        Expert expert = expertRepository.findByUserId(appointment.getExpertId());
        appointment.setExpertName(expert.getName());
        return expertAppointmentService.save(appointment);
    }

    @PutMapping("/{id}")
    public ExpertAppointment updateAppointment(@PathVariable Long id, @RequestBody ExpertAppointment appointment) {
        appointment.setId(id);
        return expertAppointmentService.save(appointment);
    }

    @DeleteMapping("/{id}")
    public Boolean deleteAppointment(@PathVariable Long id) {
        expertAppointmentService.delete(id);
        return true;
    }
} 